package org.ysh.demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@RestController
@RequestMapping("/download")
@Slf4j
public class DownloadController {

    static final int ZIP_BUFFER_SIZE = 1024 * 1024;

    @RequestMapping("/file")
    public String downloadFile(String fileName, HttpServletResponse response) {
        try {

            File file = new File("D:\\" + fileName);
            if (!file.exists()) {
                log.info("下载的文件不存在 " + file.getPath());
                return "Error";
            }
            try (InputStream ins = new FileInputStream(file);
                 BufferedInputStream bins = new BufferedInputStream(ins);
                 OutputStream outs = response.getOutputStream();
                 BufferedOutputStream bouts = new BufferedOutputStream(outs)) {
                response.setContentType("application/x-download");
                response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//                int bytesRead = 0;
                byte[] available = new byte[ins.available()];
                bins.read(available);
//                byte[] buffer = new byte[ZIP_BUFFER_SIZE];
//                while ((bytesRead = bins.read(buffer, 0, ZIP_BUFFER_SIZE)) != -1) {
//                    bouts.write(buffer, 0, bytesRead);
//                }
                byte[] encode = Base64Utils.encode(available);
                bouts.write(encode);
                bouts.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Hello";
    }

}
